import express from 'express';
import multer from 'multer';
import path from 'path'; 
const app = express();
const port = process.env.PORT || 3000;

app.use(express.json());

import { convertMarkdown } from './utils/converter.js';
import fs from 'fs';

// const upload = multer({ dest: 'uploads/' });
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadPath = '/tmp/uploads'; // Use /tmp directory
    fs.mkdir(uploadPath, { recursive: true }, (err) => {
      if (err) {
        return cb(err);
      }
      cb(null, uploadPath);
    });
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
  }
});
const upload = multer({ storage: storage });
app.get('/', (req, res) => {
  res.send('Markdown to HTML API is running!');
});

app.post('/api/convert/:platform', upload.single('mdFile'), async (req, res) => {
  const { platform } = req.params;
  let markdownContent;
  
  // console.log('Request Body:', req.body); // Removed console.log
  // console.log('Uploaded File:', req.file); // Removed console.log

  if (req.file) {
    markdownContent = await fs.promises.readFile(req.file.path, 'utf-8');
    await fs.promises.unlink(req.file.path);
  } else if (req.body && req.body.markdown) {
    markdownContent = req.body.markdown;
  } else {
    return res.status(400).send('No markdown content provided');
  }

  if (typeof markdownContent !== 'string' || markdownContent.trim() === '') {
    return res.status(400).json({ error: 'Markdown content is required.' });
  }

  const supportedPlatforms = ['wechat', 'zhihu', 'juejin', 'default'];
  if (!supportedPlatforms.includes(platform)) {
    return res.status(400).json({ error: `Unsupported platform: ${platform}. Supported platforms are: ${supportedPlatforms.join(', ')}` });
  }

  try {
    const effectivePlatform = ['wechat', 'zhihu', 'juejin'].includes(platform) ? platform : 'default';
    const html = await convertMarkdown(markdownContent, effectivePlatform, req.body.markdownTheme || 'normal', req.body.codeTheme || 'github');
    res.setHeader('Content-Type', 'text/html');
    res.send(html);
  } catch (error) {
    console.error(`Error converting markdown for platform ${platform}:`, error); // Keep console.error
    res.status(500).json({ error: 'An error occurred during conversion.' });
  }
});

app.listen(port, () => {
  // console.log(`Server listening at http://localhost:${port}`); // Removed console.log
});

export default app;